package Services

import(
	"github.com/gin-gonic/gin"
	"fmt"
	"net/http"
	"gin/Databases"
	"gin/Common"
	"encoding/json"
	"strconv"
)

type CustomTaskDetailData struct {
    DataSite string `db:"Fdata_site" json:"data_site"`
    DataTitle string `db:"Fdata_title" json:"data_title"`
    DataDate string `db:"Fdata_date" json:"data_date"`
    DataUrl string `db:"Fdata_url" json:"data_url"`
}

type DisplayTaskDetailCgi struct {
	Common.CgiBase
	DetailData []CustomTaskDetailData
}

func (cgi *DisplayTaskDetailCgi)checkTaskExist() {
	var cnt []int
	task_id, _ := strconv.Atoi(cgi.Input["task_id"])
	sql := "select count(1) from db_custom_task where Fid=? and Fentity_name=?;"
	err := Databases.Db.Select(&cnt, sql, task_id, cgi.Input["entity_name"])
	if err != nil {
		fmt.Println("query task fail, ", err)
		panic("query task fail")
	}

	if cnt[0] == 0 {
		panic("task is not exist")
	}
}

func (cgi *DisplayTaskDetailCgi)quertTaskDetail() {
	task_id, _ := strconv.Atoi(cgi.Input["task_id"])
	sql := "select Fdata_site,Fdata_title,Fdata_date,Fdata_url from db_custom_task_detail where Ftask_id =? and Fstatus = 0 order by Fdata_date desc;"
	err := Databases.Db.Select(&cgi.DetailData, sql, task_id)
	if err != nil {
		fmt.Println("exec failed, ", err)
		panic("query data fail")
	}
}

func (cgi *DisplayTaskDetailCgi)transformTask() (string){
    str, _ := json.Marshal(cgi.DetailData)
    str_res := string(str)
    return str_res
}

func (cgi *DisplayTaskDetailCgi)processParam(c *gin.Context) {
	cgi.Input["entity_name"] = c.PostForm("entity_name")
	//task_id, _ := strconv.Atoi(c.PostForm("task_id"))
	cgi.Input["task_id"] = c.PostForm("task_id")
}

func DisplayTaskDetail(c *gin.Context) {
	defer func(){
		fmt.Println("开始处理异常")
		if err:=recover();err!=nil{
			fmt.Println("error:",err)
			c.JSON(http.StatusOK, gin.H{
		        "result": -1,
		        "msg":    err,
		        "data": "{}",
		    })
		}
	}()


	var cgi DisplayTaskDetailCgi
	cgi.Init(c)
	cgi.processParam(c)
	cgi.checkTaskExist()
	cgi.quertTaskDetail()

	json_res := cgi.transformTask()

    c.JSON(http.StatusOK, gin.H{
        "result": 0,
        "msg":    "success",
        "data": json_res,
    })

}

